import React, { useState, useEffect } from "react";
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import { getCurrentUser } from '@/utils/authority';
import { Form, message, Select } from 'antd';
import { changeInit, getChannelList } from '../../service';
import { find } from "lodash";

const { Option } = Select;

export default ({ visible, type, initChannel, handleOk, handleCancel }) => {

  const [form] = Form.useForm();

  const [loading, setLoading] = useState(false);

  //下拉渠道列表，需要根据type请求不同的list
  const [ channelList, setChannelList ] = useState([]);

  const queryChannelList = async () => {
    setLoading(true);
    let typeValue = null;
    if (type == 3 || type == 1) {
      typeValue = 1
    } else if (type == 2) {
      typeValue = 4
    } else {
      typeValue = 2
    }
    const { data, success } = await getChannelList({
      isDeleted: 0,
      type: typeValue
    })
    setLoading(false);
    if (success) {
      if(!find(data, ['id', initChannel.channelId])) {
        form.setFieldsValue({
          channelId: undefined
        })
      }
      setChannelList(data);
    }
  }

  useEffect(() => {
    if(visible) {
      form.resetFields();
      queryChannelList();
    }
  }, [visible])


  //点击确定
  const onOk = () => {
    form.validateFields().then(val => {
      EditChannel(val);
    }).catch(err => {
      console.log(err);
    })
  }

  //修改发货渠道
  const EditChannel = async (val) => {
    setLoading(true);
    const { success } = await changeInit({
      ...val,
      id: initChannel.id
    })
    if (success) {
      message.success('初始化发货渠道配置修改成功');
      handleOk();
    }
    setLoading(false);
  }

  const optionChannel = channelList.map(item => {
    return <Option key={item.id} value={item.id}>{item.channelName}{getCurrentUser().uuid == item.uuid ? '(自发)' : '(第三方)'}</Option>
  })

  return (
    <CommonModal
      title="初始化发货渠道配置修改"
      visible={visible}
      onCancel={handleCancel}
      onOk={onOk}
      width={460}
    >
      <div className="form_box">
        <Form
          name="order"
          form={form}
          initialValues={{
            channelId: initChannel.channelId
          }}
        >
          <Form.Item
            label="初始化发货渠道"
            name="channelId"
            rules={[
              { required: true, message: '请选择发货渠道' },
            ]}
          >
            <Select placeholder="请选择发货渠道" style={{ width: 260 }}>
              {optionChannel}
            </Select>
          </Form.Item>
        </Form>
      </div>
      <p className="common-color13">
        注意：1.修改了初始化发货渠道后，对之前已设置过的商品的发货渠道没有影响，会对后续进来的新商品有影响<br/>2.Excel导入订单的商品若未在商品管理里存在，即会默认“自发商品”，发货渠道读取“初始化发货渠道”
      </p>
      <CommonLoading loading={loading} />
    </CommonModal>
  )
}